package com.sendi.system.util.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
/*
 *     使用示列
 *   	FtpUtil fu=new FtpUtil();
		fu.connectServer("192.168.1.47", 21, "sdnmuser", "gzsendi", "/ftptest/");
		fu.changeWorkingDirectory("/ftptest/");
       fu.uploadFile("d:/wanglang.sql", "wanglang4.sql");
       fu.download("wanglang2.sql", "d:/wanglang2.sql");
 */
public class FtpUtil {
	
	private FTPClient ftpClient;   
    public static final int BINARY_FILE_TYPE = FTP.BINARY_FILE_TYPE;   
    public static final int ASCII_FILE_TYPE = FTP.ASCII_FILE_TYPE;   
    
    /*
     * 连接 登录 更改工作目录 
     */
    public void connectServer(String server, int port, String user,   
            String password, String path) throws SocketException, IOException {   
        ftpClient = new FTPClient();   
        ftpClient.connect(server, port);   
        System.out.println("Connected to " + server + ".");   
        System.out.println("ftp reply code:"+ftpClient.getReplyCode());   
        ftpClient.login(user, password);   
     
        if (path.length() != 0) {   
         boolean c=   ftpClient.changeWorkingDirectory(path);   
         System.out.println("changeWorkingDirectory :"+c);
        }   
    }   
    /*
     * FTP.BINARY_FILE_TYPE | FTP.ASCII_FILE_TYPE   
     *  Set transform type   
     */
   
    public void setFileType(int fileType)  {  
         try {
			ftpClient.setFileType(fileType);
		} catch (IOException e) {
			e.printStackTrace();
		}   
    }  
    /*
     * FTPClient.ASCII_FILE_TYPE
     * FTPClient.BINARY_FILE_TYPE
     */
    public void setFileTransferMode(int mode)
    {
    	try {
    		
			ftpClient.setFileTransferMode(mode);
		} catch (IOException e) {
		 	e.printStackTrace();
		}
    }
    
    public void closeServer(){   
        if (ftpClient.isConnected()) {   
            try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}   
        }   
    }  
    public boolean changeWorkingDirectory(String path) throws IOException {   
        return ftpClient.changeWorkingDirectory(path);   
    }   
    public boolean createDirectory(String pathName) throws IOException {   
        return ftpClient.makeDirectory(pathName);   
    }   
    public boolean removeDirectory(String path) throws IOException {   
        return ftpClient.removeDirectory(path);   
    }   
       

    /*
     * 该方法尚未可用
     */
    private boolean removeDirectory(String path, boolean isAll)   
            throws IOException {   
           
        if (!isAll) {   
            return removeDirectory(path);   
        }   
  
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);   
        if (ftpFileArr == null || ftpFileArr.length == 0) {   
            return removeDirectory(path);   
        }   
       
        for (FTPFile ftpFile : ftpFileArr) {   
            String name = ftpFile.getName();   
            if (ftpFile.isDirectory()) {   
            		System.out.println("* [sD]Delete subPath ["+path + "/" + name+"]");                
                removeDirectory(path + "/" + name, true);   
            } else if (ftpFile.isFile()) {   
            		System.out.println("* [sF]Delete file ["+path + "/" + name+"]");                           
            		deleteFile(path + "/" + name);   
            } else if (ftpFile.isSymbolicLink()) {   
  
            } else if (ftpFile.isUnknown()) {   
  
            }   
        }   
      	 return ftpClient.removeDirectory(path);   
    }   
       
    // Check the path is exist; exist return true, else false.   
    public boolean existDirectory(String path) throws IOException {   
        boolean flag = false;   
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);   
        for (FTPFile ftpFile : ftpFileArr) {   
            if (ftpFile.isDirectory()   
                    && ftpFile.getName().equalsIgnoreCase(path)) {   
                flag = true;   
                break;   
            }   
        }   
        return flag;   
    }   
    public List<String> getFileList(String path) throws IOException {   
   
        FTPFile[] ftpFiles= ftpClient.listFiles(path);   
           
        List<String> retList = new ArrayList<String>();   
        if (ftpFiles == null || ftpFiles.length == 0) {   
            return retList;   
        }   
        for (FTPFile ftpFile : ftpFiles) {   
            if (ftpFile.isFile()) {   
                retList.add(ftpFile.getName());   
            }   
        }   
        return retList;   
    }   
  
    public boolean deleteFile(String pathName) throws IOException {   
        return ftpClient.deleteFile(pathName);   
    }   
  
   /*
    * fileName 是包含路径的与文件名称的参数 (本地)
    * newName 是新的文件名,不包含路径，使用的就是当前的工作目录 (远程)
    */
   
  
    public boolean uploadFile(String fileName, String newName)   
            throws IOException {   
        boolean flag = false;   
        InputStream iStream = null;   
        try {   
            iStream = new FileInputStream(fileName);   
            flag = ftpClient.storeFile(newName, iStream);   
        } catch (IOException e) {   
            flag = false;   
            return flag;   
        } finally {   
            if (iStream != null) {   
                iStream.close();   
            }   
        }   
        return flag;   
    }   
  
   
  
    public boolean uploadFile(InputStream iStream, String newName)   
            throws IOException {   
        boolean flag = false;   
        try {   
            // can execute [OutputStream storeFileStream(String remote)]   
            // Above method return's value is the local file stream.   
            flag = ftpClient.storeFile(newName, iStream);   
        } catch (IOException e) {   
            flag = false;   
            return flag;   
        } finally {   
            if (iStream != null) {   
                iStream.close();   
            }   
        }   
        return flag;   
    }   
  
    /* 
     * remoteFileName 当前工具目录下的远程文件名，不包含路径
     * localFileName 包含路径的本地文件名称
     */
  
    public boolean download(String remoteFileName, String localFileName)   
            throws IOException {   
        boolean flag = false;   
        File outfile = new File(localFileName);   
        OutputStream oStream = null;   
        try {   
            oStream = new FileOutputStream(outfile);   
            flag = ftpClient.retrieveFile(remoteFileName, oStream);   
        } catch (IOException e) {   
            flag = false;   
            return flag;   
        } finally {   
            oStream.close();   
        }   
        return flag;   
    }   
       
  
    public static void main(String[] args) throws Exception {
		FtpUtil fu=new FtpUtil();
		fu.connectServer("192.168.1.47", 21, "sdnmuser", "gzsendi", "/ftptest/");
		fu.changeWorkingDirectory("/ftptest/");
 	    fu.uploadFile("d:/wanglang.sql", "wanglang5.sql");
        fu.download("wanglang2.sql", "d:/wanglang3.sql");
	    fu.closeServer();
		
	}

 
    
}
